<template>
  <div class="group-list">
    <div class="list-header">
      <h3>群聊列表</h3>
      <button class="btn-icon" @click="showCreateGroup = true">
        <Icon icon="mdi:add" />
      </button>
    </div>
    
    <div class="search-box">
      <input 
        v-model="searchQuery" 
        type="text" 
        placeholder="搜索群组..." 
        class="search-input"
        @input="handleSearch"
      />
    </div>
    
    <div class="groups-container">
      <div v-if="filteredGroups.length === 0" class="empty-state">
        {{ searchQuery ? '未找到相关群组' : '暂无群组' }}
      </div>
      
      <div 
        v-for="group in filteredGroups" 
        :key="group.id" 
        class="group-item"
        :class="{ active: isActiveGroup(group.id) }"
        @click="selectGroup(group)"
      >
        <img :src="group.avatar" class="group-avatar" />
        <div class="group-info">
          <div class="group-name">{{ group.name }}</div>
          <div class="group-members">{{ group.members ? group.members.length : 0 }} 成员</div>
          <div v-if="group.lastMessage" class="group-last-message">
            {{ group.lastMessage.content }}
          </div>
        </div>
        <div class="group-meta">
          <div v-if="group.unreadCount > 0" class="unread-count">
            {{ group.unreadCount }}
          </div>
          <div v-if="group.lastMessage" class="last-message-time">
            {{ formatTime(group.lastMessage.sentAt) }}
          </div>
        </div>
      </div>
    </div>
    
    <!-- 创建群组模态框 -->
    <div v-if="showCreateGroup" class="modal-overlay" @click.self="showCreateGroup = false">
      <div class="modal-content">
        <div class="modal-header">
          <h3>创建群聊</h3>
          <button class="btn-icon" @click="showCreateGroup = false">
            <Icon icon="mdi:close" />
          </button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>群名称</label>
            <input v-model="newGroup.name" type="text" class="form-input" />
          </div>
          <div class="form-group">
            <label>群描述</label>
            <textarea v-model="newGroup.description" class="form-input"></textarea>
          </div>
          <div class="form-group">
            <label>选择成员</label>
            <div class="members-selection">
              <div 
                v-for="friend in friends" 
                :key="friend.id" 
                :class="['member-item', { selected: isMemberSelected(friend.id) }]"
                @click="toggleMemberSelection(friend.id)"
              >
                <img :src="friend.avatar" class="member-avatar" />
                <span class="member-name">{{ friend.username }}</span>
              </div>
            </div>
          </div>
          <div class="modal-actions">
            <button class="btn btn-secondary" @click="showCreateGroup = false">取消</button>
            <button class="btn btn-primary" @click="createGroup">创建</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { Icon } from '@iconify/vue';
import { useChatStore } from '@/stores/chat'
import { useAuthStore } from '@/stores/auth'

export default {
  name: 'GroupList',
  props: {
    activeGroupId: {
      type: Number,
      default: null
    }
  },
  setup(props, { emit }) {
    const chatStore = useChatStore()
    const authStore = useAuthStore()
    
    const searchQuery = ref('')
    const showCreateGroup = ref(false)
    const newGroup = ref({
      name: '',
      description: '',
      memberIds: []
    })
    
    const groups = computed(() => chatStore.groups)
    const friends = computed(() => chatStore.friends)
    
    const filteredGroups = computed(() => {
      if (!searchQuery.value) return groups.value
      
      return groups.value.filter(group => 
        group.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
        (group.description && group.description.toLowerCase().includes(searchQuery.value.toLowerCase()))
      )
    })
    
    onMounted(async () => {
      await chatStore.loadGroups()
    })
    
    const isActiveGroup = (groupId) => {
      return props.activeGroupId === groupId
    }
    
    const selectGroup = (group) => {
      emit('group-selected', group)
    }
    
    const handleSearch = () => {
      // 搜索逻辑已通过 computed 属性处理
    }
    
    const isMemberSelected = (memberId) => {
      return newGroup.value.memberIds.includes(memberId)
    }
    
    const toggleMemberSelection = (memberId) => {
      const index = newGroup.value.memberIds.indexOf(memberId)
      if (index === -1) {
        newGroup.value.memberIds.push(memberId)
      } else {
        newGroup.value.memberIds.splice(index, 1)
      }
    }
    
    const createGroup = async () => {
      if (!newGroup.value.name.trim()) {
        alert('请输入群名称')
        return
      }
      
      if (newGroup.value.memberIds.length === 0) {
        alert('请选择至少一个成员')
        return
      }
      
      const result = await chatStore.createGroup({
        name: newGroup.value.name,
        description: newGroup.value.description,
        memberIds: newGroup.value.memberIds
      })
      
      if (result.success) {
        showCreateGroup.value = false
        newGroup.value = {
          name: '',
          description: '',
          memberIds: []
        }
      } else {
        alert(result.message || '创建群组失败')
      }
    }
    
    const formatTime = (time) => {
      if (!time) return ''
      
      const date = new Date(time)
      const now = new Date()
      const diff = now - date
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      
      if (days === 0) {
        return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
      } else if (days === 1) {
        return '昨天'
      } else if (days < 7) {
        return `${days}天前`
      } else {
        return date.toLocaleDateString()
      }
    }
    
    return {
      searchQuery,
      showCreateGroup,
      newGroup,
      groups,
      friends,
      filteredGroups,
      isActiveGroup,
      selectGroup,
      handleSearch,
      isMemberSelected,
      toggleMemberSelection,
      createGroup,
      formatTime
    }
  }
}
</script>

<style scoped>
.group-list {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #e0e0e0;
}

.list-header h3 {
  margin: 0;
}

.btn-icon {
  background: none;
  border: none;
  cursor: pointer;
  padding: 0.5rem;
  border-radius: 4px;
}

.btn-icon:hover {
  background-color: #f0f0f0;
}

.search-box {
  padding: 0.5rem 1rem;
}

.search-input {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}

.groups-container {
  flex: 1;
  overflow-y: auto;
}

.empty-state {
  text-align: center;
  padding: 2rem;
  color: #999;
}

.group-item {
  display: flex;
  align-items: center;
  padding: 0.75rem 1rem;
  cursor: pointer;
  border-bottom: 1px solid #f5f5f5;
}

.group-item:hover {
  background-color: #f9f9f9;
}

.group-item.active {
  background-color: #e8f4f8;
}

.group-avatar {
  width: 50px;
  height: 50px;
  border-radius: 4px;
  margin-right: 0.75rem;
}

.group-info {
  flex: 1;
  min-width: 0;
}

.group-name {
  font-weight: 500;
  margin-bottom: 0.25rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.group-members, .group-last-message {
  font-size: 0.875rem;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.group-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.unread-count {
  background-color: #fa5151;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.75rem;
  margin-bottom: 0.25rem;
}

.last-message-time {
  font-size: 0.75rem;
  color: #999;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #e0e0e0;
}

.modal-header h3 {
  margin: 0;
}

.btn-close {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
}

.modal-body {
  padding: 1rem;
}

.form-group {
  margin-bottom: 1rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
}

.form-input {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.members-selection {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 0.5rem;
}

.member-item {
  display: flex;
  align-items: center;
  padding: 0.5rem;
  cursor: pointer;
  border-radius: 4px;
}

.member-item:hover {
  background-color: #f0f0f0;
}

.member-item.selected {
  background-color: #e8f4f8;
}

.member-avatar {
  width: 30px;
  height: 30px;
  border-radius: 4px;
  margin-right: 0.5rem;
}

.member-name {
  font-size: 0.875rem;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
  margin-top: 1rem;
}

.btn {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.btn-secondary {
  background-color: #f0f0f0;
  color: #333;
}

.btn-secondary:hover {
  background-color: #e0e0e0;
}

.btn-primary {
  background-color: #07c160;
  color: white;
}

.btn-primary:hover {
  background-color: #06ae56;
}
</style>